package com.smartkey.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.view.KeyEvent;

import com.smartkey.utils.KeyManager;

public class MediaButtonReceiver extends BroadcastReceiver {

	private static String TAG = "MediaButtonReceiver";

	private KeyManager keyManager;

	@Override
	public void onReceive(Context context, Intent intent) {
		String intentAction = intent.getAction();
		keyManager = KeyManager.getInstance(context);
		if (Intent.ACTION_MEDIA_BUTTON.equals(intentAction)) {
			KeyEvent event = (KeyEvent) intent
					.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
			if (event == null) {
				return;
			}

			int keycode = event.getKeyCode();
			int action = event.getAction();

			switch (keycode) {
			case KeyEvent.KEYCODE_HEADSETHOOK:
			case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:

				if (action == KeyEvent.ACTION_UP) {

					keyManager.handler.removeCallbacks(keyManager.runnable);
					long time = System.currentTimeMillis();
					if (keyManager.lastUpTime == 0) {
						keyManager.lastUpTime = time;
					}
					if (time - keyManager.lastUpTime < 600) {
						keyManager.count += 1;
						keyManager.lastUpTime = time;
					}
					keyManager.handler.postDelayed(keyManager.runnable, 800);
				}
				break;
			}
		}
	}
}
